<?php

namespace App\Http\Controllers\Api\Admin;

use App\AgentList;
use App\AgentOrder;
use App\Classify;
use App\Contract;
use App\Course;
use App\CourseContent;
use App\CourseCoverImg;
use App\CourseLabel;
use App\CoursePackage;
use App\CoursePackageXCourse;
use App\CourseQuestion;
use App\CourseQuestionOption;
use App\CourseSignRecord;
use App\CourseType;
use App\Files;
use App\Http\Controllers\Api\PaymentController;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\IntegralDetail;
use App\OrderContract;
use App\OrderItem;
use App\OrderRefund;
use App\Orders;
use App\SystemGroup;
use App\SystemGroupXCourse;
use App\Teacher;
use App\TeachersXClassify;
use App\User;
use App\UserGroup;
use App\UserInfo;
use App\Videos;
use App\VipInfo;
use Composer\Package\Package;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class CourseController extends Controller
{

    public function getCourseList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
        $study_type = $request->input('study_type');
        $teacher_id = $request->input('teacher_id');
        $is_featured= $request->input('is_featured');
        $need_check_in= $request->input('need_check_in');
        $status     = $request->input('status');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;
        /** @var Course $data */
        $data       = Course::where('id','>',0);
        if (trim($keyword)){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }

        if ($study_type){
            $data=$data->whereStudyType($study_type);
        }

        if (is_numeric($teacher_id)){
            $data=$data->whereTeacherId($teacher_id);
        }

        if (is_numeric($is_featured)){
            $data=$data->whereIsFeatured($is_featured);
        }

        if (is_numeric($need_check_in)){
            $data=$data->whereIsFeatured($need_check_in);
        }

        if (is_numeric($status)){
            $data=$data->whereStatus($status);
        }
        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')->offset($page * $limit)->limit($limit)->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->label_info   = CourseLabel::whereCourseId($item->id)->get();
                $temp               = CourseType::whereCourseId($item->id)->get();
                if (count($temp) > 0){
                    foreach ($temp as $item1){
                        $item1->name=Classify::getClassifyName($item1->classify_id);
                    }
                }
                $item->type_info    = $temp;
                $item->content_info = CourseContent::whereCourseId($item->id)->get();
                $item->thumb_url    = CourseCoverImg::getImgUrlByCourseId($item->id);
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }
    public function getCourseDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $course_id  =$request->input('course_id');
        $status     = $request->input('status');


        /** @var Course $data */
        $data       = Course::whereId($course_id)->first();

        if ($data){
            $data->thumb_id     = CourseCoverImg::getCourseCoverImgList($data->id);
            $data->poster_img_url = FileManager::getImgUrl($data->poster_img_id);
            $data->thumb_url    = CourseCoverImg::getCourseCoverImgList($data->id,'url');
            $data->label_info   = CourseLabel::whereCourseId($data->id)->get();
            $temp = CourseType::whereCourseId($data->id)->get();
            if (count($temp) > 0){
                foreach ($temp as $item){
                    $item->name=Classify::getClassifyName($item->classify_id);
                }
            }
            $data->type_info    = $temp;

            $temp   = CourseContent::whereCourseId($data->id)->orderBy('section_num')->get();
            if (count($temp) > 0){
                foreach ($temp as $item){
                    $arr=Videos::getNameAndUrl($item->video_id);
                    $item->video_name   = $arr['name'];
                    $item->video_url    = $arr['url'];
                }
            }
            $data->content_info = $temp;

            $temp = CourseQuestion::whereCourseId($data->id)->get();
            if (count($temp) > 0){
                foreach ($temp as $item){
                    $arr=CourseQuestionOption::whereCourseQuestionId($item->id)->get();
                    $item->option    = $arr;
                }
            }
            $data->question_info = $temp;

        }



        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
        ]);
    }
    public function getPackagesList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
        $status     = $request->input('status');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var Course $data */
        $data       = CoursePackage::where('id','>',0);
        if (trim($keyword)){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }

        if (is_numeric($status)){
            $data=$data->whereStatus($status);
        }
        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
//                $temp = CoursePackageXCourse::whereCoursePackageId($item->id)->get();
                $item->course_num   = CoursePackageXCourse::whereCoursePackageId($item->id)->count();
                $item->must_buy_num     = CoursePackageXCourse::whereCoursePackageId($item->id)->whereIsMust(1)->count();
                $item->max_sell_price    = CoursePackageXCourse::whereCoursePackageId($item->id)->max('discount_price');
                $item->min_sell_price    = CoursePackageXCourse::whereCoursePackageId($item->id)->min('discount_price');
                $item->max_discount_price    = '先对接';
                $item->min_discount_price    = '先对接';
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }
    public function getPackagesDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $package_id = $request->input('package_id');

        $data   = CoursePackage::whereId($package_id)->first();
        $temp   = CoursePackageXCourse::whereCoursePackageId($package_id)->get();
        if (count($temp) > 0){
            foreach ($temp as $item){
               $item->course_info = Course::getCourseInfo($item->course_id);
               $item->reduce_amount = $item->course_info ? ($item->course_info->price - $item->discount_price) : '-';
            }
        }
        if ($data){
            $data->course_arr=$temp;
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
        ]);
    }

    public function getCourseTypeList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
        $status     = $request->input('status');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var Classify $data */
        $data = Classify::where('id','>',0);
        if (trim($keyword)){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }

        if (is_numeric($status)){
            $data=$data->whereStatus($status);
        }

        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();

        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }
    public function getTeacherList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var Teacher $data */
        $data = Teacher::where('id','>',0);
        if (trim($keyword)){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }

        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->photo_url = FileManager::getImgUrl($item->photo_id);

                $thatClassifyIds = TeachersXClassify::whereTeachersId($item->id)->pluck("classify_id")->toArray();

                $thatClassifyArr = Classify::whereIn("id",$thatClassifyIds)->get();

                $item->classify_list = $thatClassifyArr;
            }
        }

        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }
    public function getSystemGroupList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
        $status     = $request->input('status');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var SystemGroup $data */
        $data       = SystemGroup::where('id','>',0);
        if (trim($keyword)){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }

        if (is_numeric($status)){
            $data=$data->whereStatus($status);
        }
        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->course_info=SystemGroupXCourse::getGroupCourse($item->id);
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }
    public function getSystemGroupDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $group_id = $request->input('group_id');

        $data   = SystemGroup::whereId($group_id)->first();
        if (!$data)
            return response()->json(['level' => 'error','message' => '数据不存在','data' =>[]]);
        $group_course = SystemGroupXCourse::getGroupCourse($data->id);

        $data->group_course = $group_course;


        $temp   = UserGroup::whereSystemGroupsId($data->id)->get();
        if (count($temp) > 0){
            foreach ($temp as $item){
                $item->group_owner_info = UserInfo::getUserInfo($item->user_id);
            }
        }
        $data->user_group = $temp;
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
        ]);
    }
    public function getOrderList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
//        $status     = $request->input('status');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var Orders $data */
        $data       = Orders::where('id','>',0)->whereNull("deleted_at");
        if (trim($keyword)){
            $userIds = UserInfo::where('nickname','like','%'.trim($keyword).'%')
                ->orWhere('realname','like','%'.trim($keyword).'%')
                ->pluck('user_id')
                ->toArray();
           $data=$data->whereIn('user_id',$userIds);
        }

        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            /** @var Orders $item */
            foreach ($data as $item){
                $item->order_item   = OrderItem::getOrderItem($item->id);
                $item->user_info    = UserInfo::getUserInfo($item->user_id);
                $item->vip_type_name = VipInfo::getVipTypeName($item->vip_type);

                $item->is_refund = 0;
                $orderRefund = OrderRefund::whereOrderId($item->id)->whereStatus(1)->first();
                if($orderRefund){
                    $item->is_refund = 1;
                }

                $item->contract_list = OrderContract::getOrderContractList($item->id);

                if($item->package_id != 0){
                    $item->type_name = '套餐订单';
                }elseif($item->group_id != 0){
                    $item->type_name = '拼团订单';
                }else{
                    $item->type_name = '常规订单';
                }

                if($item->review == 1){
                    $item->review_name = '通过';
                }elseif($item->review == 2){
                    $item->review_name = '拒绝';
                }else{
                    $item->review_name = '审核中';
                }

                if($item->pay_way == 'wechatpay'){
                    $item->pay_way_name = '微信支付';
                }elseif($item->pay_way == 'alipay'){
                    $item->pay_way_name = '支付宝支付';
                }elseif($item->pay_way == 'integralpay'){
                    $item->pay_way_name = '积分支付';
                }
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }

    /**
     * 订单审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function orderReview(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $type    = $request->input('type') ?? 'refuse';
        $orderId = $request->input('order_id') ?? 0;

        $orders = Orders::whereId($orderId)->first();
        if(!$orders)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        $user = User::whereId($orders->user_id)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '下单用户不存在']);

        if($orders->is_pay != 1)
            return response()->json(['level' => 'error','message' => '订单未支付']);

        if($orders->review > 0)
            return response()->json(['level' => 'error','message' => '订单已审核']);

        if($type == 'pass'){
            $orders->review = 1;
            $orders->save();

            $agentOrder = AgentOrder::whereOrderNum($orders->order_num)->first();
            if($agentOrder){
                $agent = AgentList::whereUserId($agentOrder->agent_user_id)->first();
                if($agent){
                    $agent->balance += $agentOrder->agent_fee;
                    $agent->save();
                }

                $agentOrder->status = 1;
                $agentOrder->save();
            }

            $orderItemList = OrderItem::whereOrderId($orders->id)->get();
            if(count($orderItemList) > 0){
                foreach ($orderItemList as $orderItem) {
                    $course = Course::whereId($orderItem->course_id)->first();
                    if($course && $course->is_upgrade_vip == 1){
                        $vipInfo = VipInfo::whereUserId($orders->user_id)->whereType("time")->first();
                        if(!$vipInfo){
                            $vipInfo = new VipInfo();
                            $vipInfo->user_id  = $orders->user_id;
                            $vipInfo->type     = "time";
                            $vipInfo->price    = 0.00;
                            $vipInfo->end_time = date("Y-m-d H:i:s",time() + 365 * 86400);
                            $vipInfo->save();
                        }else{
                            if(strtotime($vipInfo->end_time) <= time()){
                                $vipInfo->end_time = date("Y-m-d H:i:s",time() + 365 * 86400);
                                $vipInfo->save();
                            }
                        }
                    }
                }
            }

            $data = [
                'touser' => $user->wx_openid,
                'template_id' => '-DhTo4jI_2WBujx3uxOswncVEMy6FyE-zdXSimcvEw4',
                'page' => 'pages/myCourse/myCourse',
                'data' => [
                    "phrase1" => [
                        "value" => '通过'
                    ],
                    "date2" => [
                        "value" => date("Y-m-d H:i")
                    ],
                    "character_string4" => [
                        "value" => $orders->order_num
                    ]
                ]
            ];
            WechatLogin::sendSubscribeMessage($data);
        }else{
            $orders->review = 2;
            $orders->save();

            if($orders->is_pay == 1){
                try {
                    $refundNum = ToolsManager::makeBRefundNum();
                    $refundResult = PaymentController::Refund($orders,'退款',$refundNum);
                } catch (\Exception $e){
                    Log::error("orderReview(订单审核拒绝)=>退款错误:" . $e->getMessage());
                }

                if($refundResult && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
                    $newActivityGroupRefund = new OrderRefund();
                    $newActivityGroupRefund->order_id                          = $orders->id;
                    $newActivityGroupRefund->order_num                         = $orders->order_num;
                    $newActivityGroupRefund->refund_amount                     = $orders->pay_amount;
                    $newActivityGroupRefund->refund_num                        = $refundNum;
                    $newActivityGroupRefund->save();
                }else{
                    Log::error("orderReview(订单审核拒绝)=>" . isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '申请退款失败');
                }
            }

            $data = [
                'touser' => $user->wx_openid,
                'template_id' => '-DhTo4jI_2WBujx3uxOswncVEMy6FyE-zdXSimcvEw4',
                'page' => 'pages/myCourse/myCourse',
                'data' => [
                    "phrase1" => [
                        "value" => '不通过'
                    ],
                    "date2" => [
                        "value" => date("Y-m-d H:i")
                    ],
                    "character_string4" => [
                        "value" => $orders->order_num
                    ]
                ]
            ];
            WechatLogin::sendSubscribeMessage($data);
        }

        return response()->json(['level' => 'success','message' => '操作成功']);
    }

    /**
     * 设置订单合同
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function setOrderContract(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $contractIds = $request->input('contract_ids');
        $orderId = $request->input('order_id') ?? 0;

        $orders = Orders::whereId($orderId)->first();
        if(!$orders)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if(is_array($contractIds) && count($contractIds) > 0){
            $contractIdArr = OrderContract::whereOrderId($orderId)->pluck('contract_id')->toArray();

            $insert = array_diff($contractIds,$contractIdArr);
            $delete = array_diff($contractIdArr,$contractIds);

            if(count($insert) > 0){
                foreach ($insert as $item) {
                    $newOrderContract = new OrderContract();
                    $newOrderContract->order_id = $orderId;
                    $newOrderContract->contract_id = $item;
                    $newOrderContract->save();
                }
            }

            if(count($delete) > 0){
                OrderContract::whereOrderId($orderId)->whereIn('contract_id',$delete)->delete();
            }
        }else{
            OrderContract::whereOrderId($orderId)->delete();
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 上传合同文件
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function uploadContract(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $uploadFile = $request->file('file');

        if(!$request->hasFile('file'))
            return response()->json(['level'=>'error','message'=>'文件不存在']);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'文件上传失败']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile,$fileName);

        if($fileModel){
            $ContractModel = Contract::whereFileId($fileModel->id)->first();
            if(!$ContractModel){
                $ContractModel = new Contract();
                $ContractModel->file_id = $fileModel->id;
                $ContractModel->name    = $fileModel->file_name;
                $ContractModel->type    = $fileModel->file_type;
                $ContractModel->save();
            }
        }else{
            $ContractModel = null;
        }

        if(!is_null($ContractModel)){
            $ContractModel->contract_url = FileManager::getOrderContractUrl($ContractModel->id);
            return response()->json(['level'=>'success','message'=>'文件上传成功','data'=>$ContractModel]);
        }

        $ContractModel->contract_url = FileManager::getOrderContractUrl(0);

        return response()->json(['level'=>'success','message'=>'文件上传成功','data'=>$ContractModel]);
    }

    public function getCourseSignRecord(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $course_id  = $request->input('course_id');
        $user_id    = $request->input('user_id');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        $data = CourseSignRecord::where('id','>',0);
        if ($course_id){
            $data=$data->whereCourseId($course_id);
        }

        if ($user_id){
            $data=$data->whereUserId($user_id);
        }

        if ($start_time){
            $data = $data->where('created_at','>=',$start_time);
        }

        if ($end_time){
            $data = $data->where('created_at','<=',$end_time);
        }
        $page_info['total'] = $data->count();
        $data=$data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->course_info  = Course::getCourseInfo($item->course_id);
                $item->user_info    = CommonManager::getUserBasicInfo($item->user_id);
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$page_info]);

    }
    public function getCourseJoinInList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $course_id  = $request->input('course_id');
        $user_id    = $request->input('user_id');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page = $page-1;
        /** @var OrderItem $data */
        $data = OrderItem::where('id','>',0);
        if ($course_id){
            $data = $data->whereCourseId($course_id);
        }
        if ($user_id){
            $data = $data->whereUserId($course_id);
        }
        if ($start_time){
            $data = $data->where('created_at','>=',$start_time);
        }
        if ($end_time){
            $data = $data->where('created_at','<=',$end_time);
        }
        $order_ids = $data->pluck('order_id')->toArray();
        $success_ids = Orders::whereIn('id',$order_ids)
            ->whereIsPay(1)
            ->whereIsSuccess(1)
            ->pluck('id')
            ->toArray();
        $data = $data->whereIn('order_id',$success_ids);
        $page_info['total'] = $data->count();

        $data = $data->limit($limit)
            ->offset($page * $limit)
            ->get();
        $result = [];
        if (count($data) > 0){
            foreach ($data as $item){
                $userInfo = UserInfo::getUserInfo($item->user_id);
                $item->user_info = $userInfo;
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result,'page_info'=>$page_info]);

    }

    public function setCourse(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id             = $request->input('id');
        $thumb_id       = $request->input('thumb_id');
        $name           = $request->input('name');
        $desc           = $request->input('desc');
        $price          = $request->input('price');
        $priceDesc      = $request->input('price_desc');
        $numVipPrice    = $request->input('num_vip_price');
        $timeVipPrice   = $request->input('time_vip_price');
        $integral       = $request->input('integral');
        $study_type     = $request->input('study_type');
        $address        = $request->input('address');
        $introduce      = $request->input('introduce');
        $targetPopulation = $request->input('target_population') ?? '';
        $teacher_id     = $request->input('teacher_id');
        $is_featured    = $request->input('is_featured');
        $isAgentPromotion = $request->input('is_agent_promotion') ?? 0;
        $firstRatio = $request->input('first_ratio') ?? 0;
        $secondaryRatio = $request->input('secondary_ratio') ?? 0;
        $rewardRule = $request->input('reward_rule') ?? '';
        $posterImgId = $request->input('poster_img_id') ?? 0;
        $fictitiousSellingNum    = $request->input('fictitious_selling_num') ?? 0;
        $isUpgradeVip = $request->input('is_upgrade_vip') ?? 0;
        $showPrice = $request->input('show_price') ?? 0;
        $sort           = $request->input('sort');
        $need_check_in      = $request->input('need_check_in');
        $check_in_integral  = $request->input('check_in_integral');
        $exchange_integral  = $request->input('exchange_integral');
        $share_integral     = $request->input('share_integral');
        $check_per_day      = $request->input('check_per_day');
        $isIntegralExchange = $request->input('is_integral_exchange',0);
        $status     =$request->input('status');

        $label_arr  = $request->input('label_arr');
        $type_arr   = $request->input('type_arr');
        $contents_arr = $request->input('contents_arr');
        $question_arr = $request->input('question_arr');
//        $=$request->input('');

        if(!$showPrice)
            return response()->json(['level' => 'error','message' => '请填写原价']);

        if(!$price && !$timeVipPrice)
            return response()->json(['level' => 'error','message' => '会员价与优惠价至少填写一项']);

        if($price && $timeVipPrice)
            return response()->json(['level' => 'error','message' => '会员价与优惠价只能填写一项']);

        if($isAgentPromotion == 1){
            if(empty($firstRatio))
                return response()->json(['level' => 'error','message' => '请填写一级佣金比率']);

            if(empty($secondaryRatio))
                return response()->json(['level' => 'error','message' => '请填写二级佣金比率']);

            if(empty($rewardRule))
                return response()->json(['level' => 'error','message' => '请填写奖励规则']);

            if(empty($posterImgId))
                return response()->json(['level' => 'error','message' => '请上传海报图']);

        }

        if (is_numeric($id)){
            $record=Course::whereId($id)->first();
            if (!$record)
                $record=new Course();
        } else {
            $record=new Course();
        }
//        $record->thumb_id   = $thumb_id ?? 0;
        $record->name       = $name     ?? '';
        $record->desc       = $desc     ?? '';
        $record->price      = $price    ?? 0;
        $record->show_price      = $showPrice    ?? 0;
        $record->price_desc = $priceDesc ?? '';
        $record->num_vip_price = $numVipPrice    ?? 0;
        $record->time_vip_price = $timeVipPrice    ?? 0;
        $record->integral   = $integral ?? 0;
        $record->study_type = $study_type     ?? '';
        $record->address    = $address     ?? '';
        $record->introduce  = $introduce     ?? '';
        $record->target_population  = $targetPopulation;
        $record->teacher_id = $teacher_id     ?? 0;
        $record->is_featured= $is_featured     ?? 0;
        $record->is_agent_promotion = $isAgentPromotion;
        $record->first_ratio = $firstRatio;
        $record->secondary_ratio = $secondaryRatio;
        $record->reward_rule = $rewardRule;
        $record->poster_img_id = $posterImgId;
        $record->sort       = $sort     ?? 0;
        $record->need_check_in = $need_check_in     ?? 0;
        $record->check_per_day = $check_per_day     ?? 0;
        $record->check_in_integral = $check_in_integral     ?? 0;
        $record->exchange_integral = $exchange_integral     ?? 0;
        $record->share_integral = $share_integral     ?? 0;
        $record->is_integral_exchange = $isIntegralExchange;
        $record->fictitious_selling_num = $fictitiousSellingNum;
        $record->is_upgrade_vip = $isUpgradeVip;
        $record->status     = $status ? 1 : 0;
        $record->save();

        if(is_array($thumb_id) && count($thumb_id) > 0){
            $thumbArr = CourseCoverImg::whereCourseId($record->id)
                ->pluck('img_id')
                ->toArray();

            $del_thumb = array_diff($thumbArr,$thumb_id);
            $add_thumb = array_diff($thumb_id,$thumbArr);

            if(count($add_thumb) > 0){
                foreach ($add_thumb as $item) {
                    if(($item ?? false)){
                        $newThumb = new CourseCoverImg();
                        $newThumb->course_id = $record->id;
                        $newThumb->img_id    = $item;
                        $newThumb->save();
                    }
                }
            }

            if(count($del_thumb) > 0){
                CourseCoverImg::whereCourseId($record->id)
                    ->whereIn('img_id',$del_thumb)
                    ->delete();
            }
        }else{
            CourseCoverImg::whereCourseId($record->id)->delete();
        }

        if (count($label_arr) > 0){
            $exist_label=CourseLabel::whereCourseId($record->id)
                ->pluck('name')->toArray();
            $del_arr=array_diff($exist_label,$label_arr);
            $add_arr=array_diff($label_arr,$exist_label);
            if (count($add_arr) > 0)
                foreach ($add_arr as $item){
                    if (($item ?? false)){
                        $label=new CourseLabel();
                        $label->course_id   =$record->id;
                        $label->name        =$item;
                        $label->save();
                    }
                }
            if (count($del_arr) > 0){
                CourseLabel::whereCourseId($record->id)
                    ->whereIn('name',$del_arr)
                    ->delete();
            }
        } else {
            CourseLabel::whereCourseId($record->id)->delete();
        }

        if (count($type_arr) > 0){
            $exist_types=CourseType::whereCourseId($record->id)
                ->pluck('classify_id')->toArray();
            $del_arr=array_diff($exist_types,$type_arr);
            $add_arr=array_diff($type_arr,$exist_types);
            if (count($add_arr) > 0)
                foreach ($add_arr as $item){
                    if (($item ?? false)){
                        $type=new CourseType();
                        $type->course_id   =$record->id;
                        $type->classify_id =$item;
                        $type->save();
                    }
                }
            if (count($del_arr) > 0){
                CourseType::whereCourseId($record->id)
                    ->whereIn('classify_id',$del_arr)
                    ->delete();
            }
        } else {
            CourseType::whereCourseId($record->id)->delete();
        }

        if (count($contents_arr) > 0){
//            $contents_arr=[
//                'id'=>0,
//                '....'
//            ];
            $exist_content_id=CourseContent::whereCourseId($record->id)
                ->pluck('id')->toArray();
            $input_ids=[];

            foreach ($contents_arr as $item){
                $thisContent=CourseContent::whereId($item['id'])->whereCourseId($record->id)->first();
                if (!$thisContent){
                    $thisContent= new CourseContent();
                    $thisContent->course_id=$record->id;
                }
                $thisContent->section_num=$item['section_num'] ?? '';
                $thisContent->section_name=$item['section_name'] ?? '';
                $thisContent->video_id=$item['video_id'] ?? 0;
                $thisContent->file_id=$item['file_id'] ?? 0;
                $thisContent->allow_try=$item['allow_try'] ?? 0;
                $thisContent->attempt_learn_time=$item['attempt_learn_time'] ?? 0;
                $thisContent->save();
                if ($item['id']){
                    array_push($input_ids,$item['id']);
                }
            }
            $del_arr=array_diff($exist_content_id,$input_ids);
            CourseContent::whereCourseId($record->id)->whereIn('id',$del_arr)->delete();

        } else {
            CourseContent::whereCourseId($record->id)->delete();
        }
        if (count($question_arr) > 0){
//            $question_arr=[
//                [
//                    'id'=>0,//0新增,具体值编辑
//                    'question'=>'腾讯公司成立于那一年',
//                    'sort'=>1,
//                    'integral'=>1,
//                    'limit_num'=>1,
//                    'option'=>[
//                        ['id'=>0,'option'=>'1919','is_true'=>0],
//                        ['id'=>0,'option'=>'1949','is_true'=>0],
//                        ['id'=>0,'option'=>'1988','is_true'=>0],
//                        ['id'=>0,'option'=>'1997','is_true'=>1],
//                    ]
//                ],
//                [
//                    'id'=>0,//0新增,具体值编辑
//                    'question'=>'网易公司成立于那一年',
//                    'option'=>[
//                        ['id'=>0,'option'=>'1919','is_true'=>0],
//                        ['id'=>0,'option'=>'1949','is_true'=>0],
//                        ['id'=>0,'option'=>'1988','is_true'=>0],
//                        ['id'=>0,'option'=>'1997','is_true'=>1],
//                    ]
//                ]
//
//            ];
            $exist_question_id=CourseQuestion::whereCourseId($record->id)
                ->pluck('id')->toArray();
            $input_ids=[];
            foreach ($question_arr as $item) {
                if ($item['question']){
                    $thisQuestion = CourseQuestion::whereId($item['id'])->whereCourseId($record->id)->first();
                    if (!$thisQuestion){
                        $thisQuestion=new CourseQuestion();
                        $thisQuestion->course_id=$record->id;
                    }
                    $thisQuestion->question = $item['question'] ?? '';
                    $thisQuestion->sort     = $item['sort']     ?? 0;
                    $thisQuestion->integral = $item['integral'] ?? 0;
                    $thisQuestion->limit_num = $item['limit_num'] ?? 0;
                    $thisQuestion->save();
                    if ($item['id']){
                        array_push($input_ids,$item['id']);
                    }
                    if (count($item['option']) > 0){
                        foreach ($item['option'] as $option){
//                            \Log::notice('$option_is_Object='.is_object($option).'__is_array='.is_array($option));
//                            \Log::notice('$option[option]='.$option['option']);
                            if ($option['option'] ?? false){
                                if(!isset($option['id'])){
                                    $option['id']=0;
                                }
                                $thisOption = CourseQuestionOption::whereId($option['id'])
                                    ->whereCourseQuestionId($thisQuestion->id)->first();
                                if (!$thisOption){
                                    $thisOption                     = new CourseQuestionOption();
                                    $thisOption->course_question_id = $thisQuestion->id;
                                }
                                $thisOption->option     = $option['option']     ?? '';
                                $thisOption->is_true    = $option['is_true']    ?? 0;
                                $thisOption->save();
                            }
                        }
                    }
                }

            }
            $del_arr=array_diff($exist_question_id,$input_ids);
            CourseQuestion::whereCourseId($record->id)->whereIn('id',$del_arr)->delete();
        } else {
            CourseQuestion::whereCourseId($record->id)->delete();
        }

        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);

    }

    public function getTeacherClassify(Request $request){
        $allClassify = Classify::whereType("teacher")->orderBy("sort","asc")->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allClassify]);
    }

    public function setTeacher(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $photo_id   = $request->input('photo_id');
        $name       = $request->input('name');
        $phone      = $request->input('phone');
        $email      = $request->input('email');
        $sex        = $request->input('sex');
        $area       = $request->input('area');
        $desc       = $request->input('desc');
        $detail     = $request->input('detail');
        $classifyIds = $request->input('classify_ids');

        if(!is_null($classifyIds)){
            if(!is_array($classifyIds)){
                return response()->json(['level' => 'error','message' => '分类格式错误！']);
            }
        }

        if (is_numeric($id)){
            $record=Teacher::whereId($id)->first();
            if (!$record)
                $record=new Teacher();
        } else {
            $record=new Teacher();
        }
        $record->photo_id   =$photo_id  ?? 0;
        $record->name       =$name      ?? '';
        $record->phone      =$phone     ?? '';
        $record->email      =$email     ?? '';
        $record->sex        =$sex       ?? '';
        if (is_array($area) && count($area) > 0){
            $area_str='';
            foreach ($area as $value){
                if ($area_str)
                    $area_str=$area_str.'/'.$value;
                else
                    $area_str=$area_str.$value;
            }
            $record->area       =$area_str ?? '';
        }

        $record->desc       =$desc      ?? '';
        $record->detail     =$detail    ?? '';
        $record->save();

        if(!is_null($classifyIds)){
            TeachersXClassify::whereTeachersId($record->id)->delete();
            if(count($classifyIds) > 0){
                foreach ($classifyIds as $classifyId){
                    $thatClassify = new TeachersXClassify();
                    $thatClassify->classify_id = $classifyId;
                    $thatClassify->teachers_id = $record->id;
                    $thatClassify->save();
                }
            }
        }

        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);
    }
    public function setPackages(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $name       = $request->input('name');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $group      = $request->input('activity_group');
        $status     = $request->input('status');
        $course_arr = $request->input('course_arr');
//        $course_arr=[
//            [
//                'course_id'=>1,
//                'is_must'=>1,
//                'discount_prise'=>98,
//                'remain_num'=>98,
//            ],
//            [
//                'course_id'=>2,
//                'is_must'=>0,
//                'discount_prise'=>118,
//                'remain_num'=>118,
//            ]
//        ];
        if (is_numeric($id)){
            $packages=CoursePackage::whereId($id)->first();
            if (!$packages)
                $packages=new CoursePackage();
        } else {
            $packages=new CoursePackage();
        }
        $packages->name=$name;
        $packages->start_time=$start_time ?? null;
        $packages->end_time=$end_time ?? null;
        $packages->activity_group='all_user';
        $packages->status=$status ? 1 : 0;
        $packages->save();

        $exist_course_id=CoursePackageXCourse::whereCoursePackageId($packages->id)
            ->pluck('id')->toArray();
        $input_ids=[];
        if (count($course_arr) > 0){
            foreach ($course_arr as $item){
//                $exist=CoursePackageXCourse::whereCoursePackageId($packages->id)->whereCourseId($item['course_id'])->first();
                if ($item['course_id']){
                    $exist=CoursePackageXCourse::whereCoursePackageId($packages->id)
                        ->whereId($item['id'])->first();
                    if (!$exist){
                        $exist=new CoursePackageXCourse();
                        $exist->course_package_id   = $packages->id;
                    }
                    $exist->course_id           = $item['course_id'];
                    $exist->is_must         = $item['is_must'] ? 1 : 0;
                    $exist->discount_price  = $item['discount_price'] ?? 0;
                    $exist->remain_num  = $item['remain_num'] ?? 0;
                    $exist->save();
                    if ($item['id']){
                        array_push($input_ids,$item['id']);
                    }
                }
            }
            $del_arr=array_diff($exist_course_id,$input_ids);
            CoursePackageXCourse::whereCoursePackageId($packages->id)->whereIn('id',$del_arr)->delete();
        } else {
            CoursePackageXCourse::whereCoursePackageId($packages->id)->delete();
        }
        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);
    }
    public function setSystemGroup(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $name       = $request->input('name');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $time_limit = $request->input('time_limit');
        $require_num= $request->input('require_num');
        $group      = $request->input('activity_group');
        $status     = $request->input('status');
        $course_arr = $request->input('course_arr');
//        $course_arr=[
//            [
//                'course_id'=>1,
//                'group_price'=>98,
//            ],
//            [
//                'course_id'=>2,
//                'group_price'=>118,
//            ]
//        ];
        if (is_numeric($id)){
            $group=SystemGroup::whereId($id)->first();
            if (!$group)
                $group=new SystemGroup();
        } else {
            $group=new SystemGroup();
        }
        $group->name=$name;
        $group->start_time  = $start_time   ?? null ;
        $group->end_time    = $end_time     ?? null;
        $group->time_limit  = $time_limit   ?? 0;
        $group->require_num = $require_num  ?? 0;
        $group->activity_group='all_user';
        $group->status=$status ? 1 :0;
        $group->save();
        $exist_group_id=SystemGroupXCourse::whereSystemGroupsId($group->id)
            ->pluck('id')->toArray();
        $input_ids=[];
        if (count($course_arr) > 0){
            foreach ($course_arr as $item){
                if ($item['course_id']){
                    $exist=SystemGroupXCourse::whereSystemGroupsId($group->id)
                        ->whereId($item['id'])->first();
                    if (!$exist){
                        $exist=new SystemGroupXCourse();
                        $exist->system_groups_id    = $group->id;
                    }
                    $exist->course_id           = $item['course_id'];
                    $exist->group_price  = $item['group_price'] ?? 0;
                    $exist->save();
                    if ($item['id']){
                        array_push($input_ids,$item['id']);
                    }
                }
            }
            $del_arr=array_diff($exist_group_id,$input_ids);
            SystemGroupXCourse::whereSystemGroupsId($group->id)->whereIn('id',$del_arr)->delete();
        } else {
            SystemGroupXCourse::whereSystemGroupsId($group->id)->delete();
        }
        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);
    }
    public function setCourseType(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $name       = $request->input('name');
        $desc       = $request->input('desc');
        $sort       = $request->input('sort');
        $status     = $request->input('status');

        if (is_numeric($id)){
            $record=Classify::whereId($id)->whereType('course')->first();
            if (!$record)
                $record=new Classify();
        } else {
            $record=new Classify();
        }
        $record->name=$name;
        $record->desc=$desc;
        $record->sort=$sort ?? 1;
        $record->type='course';
        $record->status=$status ? 1: 0;
        $record->save();

        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);
    }

    public function setTeacherClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $name       = $request->input('name');
        $desc       = $request->input('desc');
        $sort       = $request->input('sort');
        $status     = $request->input('status');

        if (is_numeric($id)){
            $record=Classify::whereId($id)->whereType('teacher')->first();
            if (!$record)
                $record=new Classify();
        } else {
            $record=new Classify();
        }
        $record->name=$name;
        $record->desc=$desc;
        $record->sort=$sort ?? 1;
        $record->type='teacher';
        $record->status=$status ? 1: 0;
        $record->save();

        return response()->json([
            'level'=>'success',
            'message'=>'设置成功',
        ]);
    }


    public function delTeacher(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord=Teacher::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'老师不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }

    public function delTeacherClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord = Classify::whereId($id)->whereType("teacher")->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'分类不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }

    public function delCourseType(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord=Classify::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'类型不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }
    public function delSystemGroup(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord=SystemGroup::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'记录不存在',]);
        $thisRecord->delete();
        SystemGroupXCourse::whereSystemGroupsId($thisRecord->id)->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }
    public function delPackages(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord=CoursePackage::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'记录不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }
    public function delCourse(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id         = $request->input('id');
        $thisRecord=Course::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'记录不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);
    }

    public function delQuestion(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id         = $request->input('id');

        $thisRecord=CourseQuestion::whereId($id)->first();
        if (!$thisRecord)
            return response()->json(['level'=>'error', 'message'=>'记录不存在',]);
        $thisRecord->delete();
        return response()->json(['level'=>'success', 'message'=>'删除成功',]);

    }
    public function courseSign(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $payload = $request->input('payload');
        if (!$payload)
            return response()->json(['level' => 'error','message' => '参数错误！']);
        try{
            $end    = substr($payload,-5);
            $prefix = substr($payload,0,-5);
            $prefixDec = hexdec($prefix);
            $start  = $prefixDec / $end;
            \Log::notice("payload=>$payload,end=>$end,prefix=>$prefix,prefixDec=>$prefixDec,start=>$start");
            if ($prefixDec % $end != 0)
                return response()->json(['level' => 'error','message' => '签到错误']);
            $orderItem = OrderItem::whereId($start)->first();
            if (!$orderItem){
                return response()->json(['level'=>'error','message'=>'没有该课程的购买信息','data'=>[]]);
            }
            $order=Orders::whereId($orderItem->order_id)->first();
            if (!$order)
                return response()->json(['level'=>'error','message'=>'没有该课程的订单信息','data'=>[]]);
            if($order->is_pay == 0)
                return response()->json(['level'=>'error','message'=>'该课程的订单还没有支付','data'=>[]]);
            if($order->is_success == 0)
                return response()->json(['level'=>'error','message'=>'该课程购买不成功','data'=>[]]);
            $courseSign = CourseSignRecord::whereUserId($orderItem->user_id)
                ->orderByDesc('id')
                ->first();
            if ($courseSign){
                if ((strtotime($courseSign->created_at) + 90) >= time()){
                    if ($courseSign->course_id == $orderItem->course_id){
                        return response()->json(['level'=>'error','message'=>'90秒内不能重复签到','data'=>[]]);
                    } else {
                        $courseSign->course_id = $orderItem->course_id;
                        $courseSign->save();
                        return response()->json(['level'=>'success','message'=>'签到修改成功',
                            'data'=>
                                [
                                    'user_info'=>UserInfo::getUserInfo($orderItem->user_id),
                                    'course_info'=>Course::getCourseInfo($orderItem->course_id)
                                ]
                        ]);
                    }
                }
            }


            $record = new CourseSignRecord();
            $record->user_id    =$orderItem->user_id;
            $record->course_id  =$orderItem->course_id;
            $record->save();
            $message=IntegralDetail::addIntegralBySign($record->user_id,$record->course_id);
        } catch (\Exception $exception){
            return response()->json(['level'=>'error','message'=>$exception->getMessage(),'data'=>[]]);
        }
        return response()->json(['level'=>'success','message'=>'签到成功',
            'data'=>
            [
                'user_info'=>UserInfo::getUserInfo($orderItem->user_id),
                'course_info'=>Course::getCourseInfo($orderItem->course_id),
                'integral_message'=>$message
            ]
        ]);

    }
}
